package com.handle.common.core.utils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.handle.common.core.dto.PageDomain;
import lombok.Data;

import java.util.List;

/**
 * @author zhangqing
 * @description 这里写描述
 * @date 2021/7/20 8:07 下午
 */
@Data
public class PageUtil<T> {
    private Integer pageNum;
    private Integer pageSize;
    private Integer totalPage;
    private Integer total;
    private List<T> list;

    /**
     * 将PageHelper分页后的list转为分页信息
     */
    public static <T> PageUtil<T> restPage(List<T> list) {
        PageUtil<T> page = new PageUtil<>();
        PageInfo<T> pageInfo = new PageInfo<>(list);
        page.setTotalPage(pageInfo.getPages());
        page.setPageNum(pageInfo.getPageNum());
        page.setPageSize(pageInfo.getPageSize());
        page.setTotal((int)pageInfo.getTotal());
        page.setList(pageInfo.getList());
        return page;
    }

    /**
     * 多列排序
     */
    public static <E> Page<E> startPageSort(Integer pageNum, Integer pageSize, String sortField, String sortOrder) {
        PageDomain pageDomain = new PageDomain(pageNum,pageSize,sortField,sortOrder);
        if (StringUtils.isEmpty(sortField) || StringUtils.isEmpty(sortOrder)) {
            return PageHelper.startPage(pageNum, pageSize);
        }
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        return PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(), orderBy);
    }

    public static <E> Page<E> startPage(Integer pageNum, Integer pageSize) {
        return PageHelper.startPage(pageNum, pageSize);
    }
}
